<?php

namespace app\common\model\game;

use app\common\model\Club;
use app\common\model\Commission;
use app\common\model\Config;
use app\common\model\DiamondLog;
use app\common\model\GoldLog;
use app\common\model\room\Users;
use app\common\model\task\Lists;
use app\common\model\task\Userlog;
use app\common\model\User;
use app\common\model\user\Bindgame;
use app\common\model\user\Ranking;
use think\Db;
use think\Exception;
use think\Model;


class Record extends Model
{

    // 表名
    protected $table = 'game_record';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    // 追加属性
    protected $append = [];

    //战绩结算
    public static function settle($members, $teamId, $groups)
    {
        $room = \app\common\model\room\Lists::where('team_id', $teamId)->find();
        if ($room) {

            $room_record_num = self::where(['room_id' => $room['id']])->count();
            if ($room_record_num > 0) {
                return ['code' => 0, "msg" => "已结算"];
            }

            $insert_record = [];//战绩
            $all = Users::where("room_id", $room['id'])->sum("money", 0);
            foreach ($members as $vm) {
                $bind_where = [
                    "game_id" => $groups["game_id"],
                    "subarea_id" => $groups["subarea_id"],
                    "game_number" => $vm["roleId"]
                ];
                $user_id = Bindgame::where($bind_where)->value("user_id");
                if ($user_id) {//绑定游戏信息匹配

                    $room_user = Users::where(["room_id" => $room['id'], "user_id" => $user_id])->find();
                    if ($room_user) {//在房间内人员.复检
                        $insert_record[] = [
                            "user_id" => $user_id,
                            "room_id" => $room['id'],
                            "game_id" => $room['game_id'],
                            "mode_id" => $room['modes_id'],
                            "subarea_id" => $room['subarea_id'],
                            "level_id" => $room['levels_id'],
                            "role_id" => $vm['roleId'],
                            "money" => $room_user['money'],
                            "service" => $room_user['service'],
                            "rank" => $vm['rank'],
                        ];
                    }
                }
            }

            if (empty($insert_record)) {
                return ['code' => 0, "msg" => "房间内无人"];
            }

            Db::startTrans();
            try {
                $count = count($insert_record);
                $expenses_ratio = Config::where('name', 'expenses_ratio')->value('value', 10);//平台扣税
                $general_agent = Config::where('name', 'general_agent')->value('value', 10);//总俱乐部比例
                foreach ($insert_record as $record) {

                    $ratios = Db::name('game_rank_ratio')->where([
                        'mode_id' => $room['modes_id'], 'rank_num' => $record['rank'], "num" => $count
                    ])->value('ratio', 0);

                    $ratios = $ratios / 100;//比例调正
                    $record["reward"] = bcmul($all, $ratios, 2);
                    $record['is_allot'] = 1;

                    $service = self::division($record['service'], $record['user_id'], $expenses_ratio, $general_agent);
                    $record = array_merge($record, $service);
//                    $parent_id_one = User::where("id", $record['user_id'])->value("parent_id", 0);//获取上级
//                    $ratio_residue = 100 - $expenses_ratio;
//                    $ratio_adjust = $ratio_residue / 100;
//                    $service = bcmul($record['service'], $ratio_adjust, 4);
//                    $ratio = Commission::ratio($parent_id_one, $service);//计算佣金
//                    if ($ratio['one'] > 0) {
//                        $one = User::get($parent_id_one);
//                        if ($one) {
//
//                            $before_one = $one['diamond'];
//                            $after_one = function_exists("bcadd") ? bcadd($one['diamond'], $ratio['one'], 2) : $one['diamond'] + $ratio['one'];
//                            $one->save(['diamond' => $after_one]);
//                            DiamondLog::create([
//                                'user_id' => $one['id'], 'diamond' => $ratio['one'],
//                                'before' => $before_one, 'after' => $after_one,
//                                'memo' => "邀请收益", 'type' => 1
//                            ]);
//
//                            $two = User::get($one['parent_id']);
//                            if ($ratio['two'] > 0 && $two) {
//
//                                $club_before = $two['diamond'];
//                                $club_after = function_exists("bcadd") ? bcadd($ratio['two'], $two['diamond'], 2) : $two['diamond'] + $ratio['two'];
//                                $two->save(['diamond' => $club_after]);
//                                DiamondLog::create([
//                                    'user_id' => $two['id'], 'diamond' => $ratio['two'],
//                                    'before' => $club_before, 'after' => $club_after,
//                                    'memo' => "推广收益", 'type' => 4
//                                ]);
//                            }
//                        }
//                    }

                    $task_list = Lists::where(['location' => 'game', 'switch' => 1])->select();
                    foreach ($task_list as $value) {
                        if ($record['rank'] >= $value['standard_limit']) {
                            $status = Userlog::check($value, $record['user_id']);
                            if ($status == -1) {
                                Userlog::get_task($value['id'], $record['user_id'], 0, 1);
                            }
                        }
                    }

                    self::create($record);
                    Ranking::increase($record['user_id'], 'rank_num');//战绩数+1
                    Users::update([
                        "award" => $record['reward'],
                        "result" => "第" . $record['rank'] . "名"
                    ], ['room_id' => $record['room_id'], 'user_id' => $record['user_id']]);
                    $user = User::get($record['user_id']);
                    if ($user && $record['reward'] != 0) {
                        $before = $user['gold'];
                        $after = function_exists("bcadd") ? bcadd($user['gold'], $record['reward'], 2) : $user['gold'] + $record['reward'];
                        GoldLog::create([
                            'user_id' => $record['user_id'], 'gold' => $record['reward'],
                            'before' => $before, 'after' => $after,
                            'memo' => "对战排名获得", "type" => 1
                        ]);
                        $user->save(['gold' => $after]);
                    }
                }
                $room->status = 2;//结束
                $room->save();
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                return ['code' => 0, "msg" => $exception->getMessage()];
            }

            return ['code' => 1, "msg" => ""];
        } else {
            return ['code' => 0, "msg" => "房间未找到"];
        }
    }

    /**
     * @param $money 服务费
     * @param $user_id 用户
     * */
    public static function division($money, $user_id, $expenses_ratio, $general_agent)
    {
        $ratio_residue = 100 - $expenses_ratio;
        $ratio_adjust = $ratio_residue / 100;//扣费比例调正
        $money_kou = bcmul($money, $ratio_adjust);//平台扣费后的金额

        //总俱乐部费用
        $zong_diamond = bcmul($money, $general_agent, 2);
        $zong = User::where("club_id", 4)->find();
        if ($zong && $zong_diamond > 0) {
            $zong_before = $zong['diamond'];
            $zong_after = bcadd($zong['diamond'], $zong_diamond, 2);
            $zong->save(['diamond' => $zong_after]);
            self::diamond($zong['id'], $zong_diamond, $zong_before, $zong_after, "总俱乐部费", 99);
        }

        $array = ['one', 'two', 'three'];
        $arrays=[];
        foreach ($array as $value) {
            $parent_id = User::where("id", $user_id)->value("parent_id", 0);
            $parent = User::where("id", $parent_id)->find();//获取上级
            $parent_diamond = 0;
            if ($parent && $parent['club_id'] > 0) {
                $ratio = Club::where('id', $parent['club_id'])->value($value, 0);
                $is_deduct = Club::where('id', $parent['club_id'])->value('is_deduct', 1);
                if ($is_deduct == 1) {
                    $parent_diamond = bcmul($money_kou, $ratio, 2);
                } else {
                    $parent_diamond = bcmul($money, $ratio, 2);
                }

                if ($parent_diamond > 0) {
                    if ($value == 'one') {
                        $memo = '邀请收益';
                        $type = 1;
                    } else {
                        $memo = "推广收益";
                        $type = 4;
                    }
                    $before = $parent['diamond'];
                    $after = bcadd($parent['diamond'], $parent_diamond, 2);
                    self::diamond($parent['id'], $parent_diamond, $before, $after, $memo, $type);
                }

                $user_id = $parent['id'];
            } else {
                $user_id = 0;
            }

            $arrays[$value] = $parent_diamond;
        }

        return $arrays;
    }

    public static function diamond($user_id, $diamond, $before, $after, $memo, $type)
    {
        DiamondLog::create([
            'user_id' => $user_id, 'diamond' => $diamond,
            'before' => $before, 'after' => $after,
            'memo' => $memo, 'type' => $type
        ]);
        return true;
    }

    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function roomLists()
    {
        return $this->belongsTo('app\common\model\room\Lists', 'room_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function gameLists()
    {
        return $this->belongsTo('Lists', 'game_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function modes()
    {
        return $this->belongsTo('Modes', 'mode_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function subarea()
    {
        return $this->belongsTo('Subarea', 'subarea_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function levels()
    {
        return $this->belongsTo('Levels', 'level_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
